package org.karesz.code.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.karesz.code.managedbean.LoginManager;


/**
 * This filter is intended to filter every requests whether they are authenticated or not.
 * If authenticated, nothing happens until the user wants to logout
 * If not authenticated, then every requests will be redirected to login.xhtml
 * 
 * 
 * @author gubak
 *
 */


public class LoginFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) arg0;
		HttpServletResponse resp = (HttpServletResponse) arg1;
		LoginManager session = (LoginManager)req.getSession().getAttribute("bean");
		String url = req.getRequestURI();
		
		
		//A. if session variable is not set or false we can only reach login.xhtml
		//B. if session variable is true and we point to login.xhtml page we will be redirected to welcome.xhtml
		//C. if session variable is true and we point to logout.xhtml we will be redirected to login.xhtml and session variable will be removed
		
		
		
		if(session == null || !session.isLogged)
		{
			if(url.endsWith("xhtml") && url.indexOf("login.xhtml") < 0){
				resp.sendRedirect(req.getContextPath() + "/login.xhtml");
			}
			else arg2.doFilter(arg0, arg1);
		}
		else
			if(url.indexOf("login.xhtml") >= 0){
				resp.sendRedirect(req.getContextPath() + "/welcome.xhtml");
			}
			else 
				if(url.indexOf("logout.xhtml") >= 0){
					req.getSession().removeAttribute("bean");				
					resp.sendRedirect(req.getContextPath() + "/login.xhtml");					
				}
				else arg2.doFilter(arg0, arg1);
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
